<?php 

class AnswerModel extends ViewModel{
	public $table='answer';
	//与问题关联
	public $view=array(
		'user'=>array('_type'=>'RIGHT'),
		'answer'=>array('_on'=>'answer.uid=user.uid'),
		);
	//自动验证
	public $validate=array(
		array('answer','nonull','答案不能为空',2,3),
		);
	//自动完成格式规范化
	public $auto=array(
		array('atime','strtotime','function',2,3),
		array('athumb','_autoThumb','method',2,3),
		);
	public function _autoThumb($v)
	{
		if (empty($v)) return $v;
		$v=current($v);
		return $v['path'];
	}
	//获得所有答案
	public function getList()
	{
		$count=$this->count();
		$page=new Page($count,3);
		$data=$this->limit($page->limit())->order(" atime desc")->all();
		return array('data'=>$data,'page'=>$page->show());
	}
	//添加答案
	public function addAnswer()
	{
		$_POST['uid']=isset($_SESSION['uid'])?$_SESSION['uid']:0;
		$uid=M('question')->field('uid')->find($_POST['qid']);
		if ($_POST['uid']==$uid['uid']) {
			$this->error('自己不能回答自己的提问');
			return false;
		}
		if (empty($_POST['atime'])) {
			$_POST['atime']=time();
		}
		if ($this->create()) {
			if ($this->add($_POST)) {
				//问题答案数加1
				return M('question')->inc('anum',"qid={$_POST['qid']}",1);
			}else{
				$this->error='添加失败';
			}
		}
	}
	//编辑答案
	public function editAnswer()
	{
		if ($this->create()) {
			if ($this->save()) {
				return true;
			}else{
				$this->error='修改失败';
			}
		}
	}

	//删除答案
	public function delAnswer($aid)
	{
		$a=$this->find($aid);
		//删除问题下面对应的答案
		if (!isset($a['athumb']))unlink($a['athumb']);
		if ($this->where(" aid=$aid")->del()) {
			return true;
		}else{
			return $this->error="删除失败";
		}	
	}

}


 ?>